const http = require('http');
const webSocket = require('ws');

const server = http.createServer();
const wss = new webSocket.Server({ server });

wss.on('connection', (ws) => {
  console.log('websocket链接已打开');

  ws.on('message', (message) => {
	const msg = JSON.parse(message);
	// const {userId, message: msg} = JSON.parse(message);
	// console.log(`收到用户 ${userId} 的消息: ${msg}`);
	// console.log(`收到消息: ${msg}`);
	// Echo the message back to the client
	// ws.send(`服务器已收到: ${message}`);
	
	wss.clients.forEach(client => {
	  if (client.readyState === webSocket.OPEN) {
		// client.send(`服务器已收到:${msg}`);
		client.send(JSON.stringify(msg));
	  }
	});
  });

  ws.on('close', () => {
	console.log('客户端已断开连接');
  });
});

server.on('request', (req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/html;charset=UTF8' });
  res.end('WebSocket服务器已启动\n');
});

server.listen(8080, () => {
  console.log('服务器正在监听端口 8080');
});